package com.xiepxcc.annotation.base.controller;

import com.xiepxcc.annotation.base.anno.XParam;
import com.xiepxcc.annotation.base.service.AccessService;
import com.xiepxcc.annotation.base.validtor.UserValidtor;
import com.xiepxcc.annotation.base.validtor.group.GroupOne;
import com.xiepxcc.annotation.base.vo.AccountVO;
import com.xiepxcc.annotation.base.vo.LoginVO;
import com.xiepxcc.annotation.base.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController

public class accessControlller {

    @Autowired
    AccessService accessService;

    @RequestMapping("/access")
    String goAccess(){
        accessService.access();
        return "success access request";
    }


    @RequestMapping("/notice")
    String goNotice(){
        try {
            accessService.notice();
        } catch (Exception e) {
            return "fail notice request";
        }
        return "success notice request";
    }

    /**
     * @Valid 将收集以您即将构建的表单填写的属性。
     * 一个bindingResult对象，您可以测试并检索验证错误。
     * @param vo
     * @param bindingResult
     * @return
     */
    @RequestMapping("/login")
    String goLogin(@Valid LoginVO vo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return String.join(";",bindingResult.getAllErrors().stream().map(a->a.getDefaultMessage()).collect(Collectors.toList()));
        }
        return "success login request";
    }

    //绑定UserValidtor
//    @InitBinder
//    public void initBinder(WebDataBinder webDataBinder) {
//        webDataBinder.addValidators(new UserValidtor());
//    }
    @RequestMapping("/registered")
    String goRegistered(@Valid UserVO vo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return String.join(";",bindingResult.getAllErrors().stream().map(a->a.getDefaultMessage()).collect(Collectors.toList()));
        }
        return "success registered request";
    }

    @RequestMapping("/account")
    String goAccount(@Validated(GroupOne.class) AccountVO vo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return String.join(";",bindingResult.getAllErrors().stream().map(a->a.getDefaultMessage()).collect(Collectors.toList()));
        }
        return "success account request";
    }

    @RequestMapping("/query")
    String goQuery(@XParam("id") String userId){
        return "success query request,param: "+ userId;
    }

    @RequestMapping("/todo")
    String gotodo(){
        accessService.toDo(null);
        return "success query request,param: ";
    }


}
